<template>
  <section v-loading="firstLoading" style="height:100%;"  class="qualification-table">
    <div class="qualification-search-box">
      <!-- <el-input class="qualification-input" :placeholder="$t('common.placeholder.inputQualificationNameSearch')" v-model="keyword"></el-input> -->
      <!-- <el-button type="primary" @click="initData('search')">{{ $t('common.base.search') }}</el-button> -->
      <!-- <el-button @click="reset">{{ $t('common.base.reset') }}</el-button> -->
      <el-button v-if="allowManage" type="primary" @click="created"><i class="iconfont icon-add2" style="margin-right:6px" ></i>{{ $t('qualificationManagement.view.btn3') }}</el-button>
    </div>

    <el-table
      v-table-style
      stripe
      border
      :data="disposeFormListViewTime(dataList, columns)"
      v-loading="loading"
      v-if="dataList.length"
    >
        
      <el-table-column prop="qualificationNo" :label="$t('qualificationManagement.field.baseNo.displayName')" show-overflow-tooltip>
        <template slot-scope="{row}">
          <!-- <el-button type="text" @click="toViewPage(row.id)">{{ row.qualificationNo }}</el-button> -->
          <div>{{ row.qualificationNo }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="qualificationName" :label="$t('qualificationManagement.field.name.displayName')" show-overflow-tooltip />
      <el-table-column prop="qualificationDesc" :label="$t('qualificationManagement.field.describe.displayName')" show-overflow-tooltip />
      <el-table-column prop="taskTemplates" :label="$t('qualificationManagement.field.dealTaskType.displayName')" show-overflow-tooltip>
        <template slot-scope="{row}">
          {{ row.taskTemplates && row.taskTemplates.map(item=>{
							if(item.id == -1) {
                return $t('qualificationManagement.view.label7')
              }
							return item.name
              }).join('，') }}
        </template>
      </el-table-column>
      <el-table-column v-if="showProductType" prop="productCatalogs" :label="$t('qualificationManagement.field.dealProductType.displayName')" show-overflow-tooltip>
        <template slot-scope="{row}">
          {{ row.productCatalogs && row.productCatalogs.map(item=>{
							if(item.id == -1) {
                return $t('qualificationManagement.view.label8')
              }
							return item.name
              }).join('，') }}
        </template>
      </el-table-column>
      <el-table-column prop="startTime" :label="$t('qualificationManagement.field.startTime.displayName')" show-overflow-tooltip />
      <el-table-column prop="endTime" :label="$t('qualificationManagement.field.endTime.displayName')" show-overflow-tooltip />
      
      <el-table-column prop="attachments" :label="$t('qualificationManagement.field.certificate.displayName')" show-overflow-tooltip>
        <template slot-scope="{row}">
          <el-button v-if="row.attachments && row.attachments.length" type="text" @click="viewFiles(row.attachments)">{{ $t('common.base.view') }}</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="createType" :label="$t('qualificationManagement.field.getType.displayName')" show-overflow-tooltip>
      <template slot-scope="{row}">
          {{getConcatTypeDes(row.createType)}}
        </template>
      </el-table-column>
      <el-table-column prop="status" :label="$t('common.base.status')" show-overflow-tooltip>
        <template slot-scope="{row, $index}">
          {{ getItemStatus($index) }}
        </template>
        </el-table-column>

      <!-- <el-table-column type="index" width="100px" :label="$t('common.label.serialNumber')" show-overflow-tooltip />

            <el-table-column prop="qualificationName" :label="$t('common.label.qualificationName')" show-overflow-tooltip />

            <el-table-column prop="preliminaryExaminationTime" :label="$t('common.label.firstTrialDate')" show-overflow-tooltip />

            <el-table-column prop="reviewTime" :label="$t('common.label.reviewDate')"  show-overflow-tooltip />

            <el-table-column prop="expireTime" :label="$t('common.label.expireDate')" show-overflow-tooltip />

            <el-table-column prop="displayName" :label="$t('common.label.expireRemind')">
                <template slot-scope="{row}">
                    {{row.reminderSwitch==0 ? $t('common.base.closed') : $t('common.base.open')}}
                </template>
            </el-table-column>

            <el-table-column prop="enclosures" :label="$t('common.label.qualicationAttachment')" class="enclosures">
                <template slot-scope="{row}">
                    <div 
                        class="enclosures-image"
                        v-if="row.pics && row.pics.length"
                    >
                        <el-image 
                            :src="row.pics[0]" 
                            :preview-src-list="row.pics">
                        </el-image>
                        <span>+ {{row.pics.length}}</span>
                    </div>

                </template>
            </el-table-column> -->

      <el-table-column :label="$t('common.base.operation')" fixed="right">
        <template slot-scope="{ row, $index }">
          <template v-if="tableOperationArr(row).length <= 1">
              <div v-for="(item, index) in tableOperationArr(row)" :key="index">
                <el-button type="text" :class="item.class" @click="item.clickFnc && item.clickFnc(row)">{{item.label}}</el-button>
              </div>
            </template>
            <el-popover
              v-else
              placement="bottom"
              :visible="tableOperationShow[row.id]"
              :width="120"
              trigger="hover"
              
              popper-class="popper-style"
            >
              <template #reference>
                <span
                  class="just-cur-point c-primary"
                >{{$t('common.base.more')}}</span
                >
              </template>
              <div v-for="(item, index) in tableOperationArr(row)" :key="index"  >
                <span class="overHideCon-1 just-cur-point hover-bg-primary pad-8"  @click="(item.clickFnc && item.clickFnc(row, $index)),delete tableOperationShow[row.id]">{{item.label}}</span>
              </div>
            </el-popover>
          </template>
      </el-table-column>

    </el-table>

    <NoAuth v-if="!firstLoading && !dataList.length"/>

    <Pagination 
      v-model="page"
      @handleSizeChange="initData"
      @handleCurrentChange="initData">
    </Pagination>

    <zi-zhi-from 
      @addQualifications="addQualifications" 
      @updateQualifications="updateQualifications" 
      ref="zzFrom">
    </zi-zhi-from>

    <base-modal :show.sync="showFileModal" :title="$t('common.base.view')"
    width="500px">
    <div class="pad-16">
      <base-file-item v-for="(a, index) in showFile" :Source="showFile" :key="index" :file="a" readonly/>
    </div>
    
    </base-modal>
  </section>
</template>

<script>
import _, {cloneDeep} from 'lodash';
// <!-- 新增/编辑资质管理 -->
import ziZhiFrom from '@src/modules/serviceProvider/component/ziZhiFrom.vue';
import Page from '@model/Page';
import * as serviceProviderApi from '@src/api/serviceProviderApi';
import { getUserConcatQualification, saveQualificationManagement, editQualificationManagement, deleteQualificationManagement } from '@src/api/UserCenterApi'
import { t } from '@src/locales'
import { getResultFile } from 'src/util/uploader'

// 翻页组件
import Pagination from '../Pagination.vue'

// 暂无数据组件
import NoAuth from '../NoAuth.vue'

import { useFormTimezone } from 'pub-bbx-utils'
const { disposeFormListViewTime, disposeFormSubmitTime } = useFormTimezone()
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { localeToHttp } from '@src/modules/dept/user/util'
import { getUserTypeDes, getConcatTypeDes, } from '@src/modules/dept/user/components/qualificationManagement'
import { getRootWindow } from '@src/util/dom'
import {
  VersionControlProductMixin,
} from '@src/mixins/versionControlMixin'
export default {
  name: 'TabQualification',
  mixins:[VersionControlProductMixin],
  data: () => {
    return {
      loading:false,

      // 用于解决第一次进入直接展示暂无数据再展示数据的bug
      firstLoading:true,
            
      page:{
        total:0,
        pageSize:10,
        pageNum:1
      },

      dataList:[],

      remindCustomerDialog: false,
      pending: false,
      editedRemind: {},
      qualificationsPage: new Page(),
      params: {
        pageNum:1,
        pageSize:10,
      },
      loading:false,
      keyword:'',
      currentRow:{},
      columns: [
        // {fieldName: 'preliminaryExaminationTime', formType: 'datetime'},
        // {fieldName: 'reviewTime', formType: 'datetime'},
        // {fieldName: 'expireTime', formType: 'datetime'}
        {fieldName: 'startTime', formType: 'datetime'},
        {fieldName: 'endTime', formType: 'datetime'},
      ],
      getUserTypeDes,
      getConcatTypeDes,
      showFileModal:false,
      showFile:[],
      tableOperationShow:{}
    };
  },
  computed:{
    auth(){
      let rootWindow = getRootWindow(window)
      let init = rootWindow?._init
      init = init ? JSON.parse(init) : {}
      let auth = init.user?.auth || {}
      return auth
    },
    allowManage() {
      return !!this.auth?.NEW_QUALIFICATION_MANAGE
    },
    editQuality(){
      return (this.mode !== 'USER' && this.allowManage) || (this.mode === 'USER' && this.isMe)
    },
    showProductType(){
      return this._isShowProductType
    }
  },

  props:{
    user:{
      type:Object,
      required:true
    },
    userId:[String, Number],
    isMe:{
      type:Boolean,
      default:true
    },
    mode:[String],
  },

  components:{
    Pagination,
    NoAuth,
    ziZhiFrom
  },

  mounted() {
    this.initData();
  },

  methods: {
    disposeFormListViewTime,
    reset(){
      this.keyword = ''
      this.page.pageSize = 10
      this.page.pageNum = 1
      this.initData()
    },

    addQualifications(form){
            
      //   serviceProviderApi.addQualifications({
      //     userId:this.userId,
      //     staffId:this.user.staffId,
      //     ...form,
      //   }).then(res=>{
      //     if(res.succ){
      //       this.$message.success(res.message);
      //       this.$refs.zzFrom.closeDialog()
      //       this.initData()
      //     }else{
      //       this.$message.error(res.message)
      //     }
      //   })
      const params = localeToHttp(form)
      // return console.log(params, 'params')
      // eslint-disable-next-line no-unreachable
      let fnc = form.id ? editQualificationManagement : saveQualificationManagement
      let ids = [this.userId]
      let idKey = (this.mode === 'USER' || this.mode === 'ENGINEER') ? 'userIds' : this.mode === 'PROVIDER' ? 'providerIds' : null
      fnc({
        ...params,
        ...(form.id ? { bizId:ids} : {[idKey]:ids} ),
      }).then(res=>{
        if(res.status === 0){
          // this.$message.success(res.message);
          this.$refs.zzFrom.closeDialog()
          this.initData()
        }else{
          this.$message.error(res.message)
        }
      })
    },

    updateQualifications(form){
      this.addQualifications(form)
    },

    edit(index, type = 0){
      const item = this.dataList[index]
      this.currentRow = item
      let type_ = type === 1 ? 'note' : 'update'
      this.$refs.zzFrom.openDialog(type_, item)
    },

    deleteItem(row){
      this.$confirm(t('qualificationManagement.view.tips2'), t('common.base.toast'), {
        type: 'warning',
      }).then(() => {
        deleteQualificationManagement({ids:[row.id], qualificationId:row.qualificationId}).then(res=>{

          if(res.status !== 0){
            this.$message.error(res.message);
            return
          }

          // this.$message.success(res.message);
          this.initData()
        })
      }).catch(() => {});
    },

    /** 抓取用户数据 */
    initData(type = ''){
      const { pageSize, pageNum } = this.page;

      const params = {
        pageSize,
        pageNum,
        bizId:this.userId,
        keyword:this.keyword,
        // qualificationName:this.qualificationName
      }

      if(type === 'search'){
        this.page.pageNum = 1
        this.page.pageSize = 10
      }

      this.loading = true;

      getUserConcatQualification({...params, 
        bizeType:this.mode}).then(res => {
        const { data:{ list = [], total = 0 }, status } = res;
        this.dataList = list || [];

        // 所有图片后缀
        const suffixArr = ['bmp', 'jpg', 'jpeg', 'png', 'gif', 'JPG', 'JPEG', 'PNG', 'GIF', 'BMP']

        this.dataList.map(item => {
          // const { enclosures } = item
          // let picArr = []
          // enclosures.map(resourceData => {
          //   const { url } = resourceData;
          //   // 获取最后一个.的位置
          //   const index = url.lastIndexOf('.');
          //   // 获取后缀
          //   const ext = url.substr(index + 1);
          //   if(suffixArr.includes(ext)){
          //     picArr.push(url)
          //   }
          // })
          // item.pics = picArr
          if(item.attachments?.length){
            item.attachments = item.attachments.map(i=>getResultFile(i))
          }
          
        })
        this.page.total = total;

        this.loading = false;
        this.firstLoading = false
                
      }).catch(e=>{
        this.loading = false;
        this.firstLoading = false
        console.error('fetch task caught e', e)
      })  

    },

        
    created(){
      this.$refs.zzFrom.openDialog()
    },

    openDialog() {
      this.remindCustomerDialog = true;
    },


    toViewPage(id){
      openAccurateTab({
        type:PageRoutesTypeEnum.PageQualificationManagementView,
        key:id,
        params:`id=${id}`
      })
    },
    getItemStatus(index){
      const item = this.dataList[index]
      const time = item.endTime
      if(time){
        if(new Date().getTime() > time * 1){
          return t('qualificationManagement.view.label5')
        }else{
          return t('qualificationManagement.view.label9')
        }
      }else{
        return t('qualificationManagement.view.label9')
      }
      
    },
    viewFiles(file){
      this.showFile = file
      this.showFileModal = true
    },
    tableOperationArr(row){
      let this_ = this
      
			return [
      // {label:t('common.label.expireRemind'), clickFnc:(data, index)=>{this_.edit(index, 1)}, class:'c-primary',},
			...(this.editQuality ? [{label:t('common.base.edit'), clickFnc:(data, index)=>{this_.edit(index)}, class:'c-primary',}] : []),
			...(this.allowManage ? [{label:t('common.base.delete'), clickFnc:(data)=>{this_.deleteItem(data)}, class:'c-danger',}] : [])
			]
		}
  },

  
};
</script>

<style lang="scss" scoped>
.qualification-table {
  padding: 20px;
  .qualification-search-box {
    margin: 0 0 12px;
  }
  .qualification-input{
    width:300px;
    margin-right:10px
  }
}
.el-table{
    border-top:1px solid #E8E8E8;
    border-left:1px solid #E8E8E8;
}
::v-deep{
    .enclosures-image{
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        justify-content: space-around;
        .el-image {
            display: flex;
            .el-image__inner{
                width: 34px;
                height: 34PX;
                border-radius: 4px;
                object-fit: cover;
            }
        }
    }
}

.c-primary{
  color:$color-primary
}
.hover-bg-primary{
	&:hover{
		background-color: $color-primary-hover;
		color:$color-primary;
	}
}

</style>
<style lang="scss">
.popper-style{
	padding:0;
	width:auto;
}
</style>
